import React, { ReactNode } from 'react';
import { Table, message } from 'antd';
import './index.scss';

interface IColumns {
  title: string;
  dataIndex: string;
  align: 'left' | 'right' | 'center';
  sorter?: boolean | Function;
  width?: string | number;
  extra: { [key: string]: any };
}
interface ILoadTableProps {
  list: Object[];
  total: number;
}
type LoadTableFunc = (params: any) => Promise<ILoadTableProps>;
interface VTableWrapperProps {
  title: ReactNode;
  rightBtn?: ReactNode;
  columns: IColumns;
  dataSource: Object[] | LoadTableFunc;
  scrollX?: number | undefined;
  scrollY?: number | undefined;
  showPagination?: boolean;
  showQuickJumper?: boolean;
  pageSizeOptions?: boolean;
  reqParams?: string;
  showTotal?: boolean;
  extra?: { [key: string]: any };
}
interface IVTableWrapperState {
  dataSource: Object[];
  loading: boolean;
  pagination: {
    total: number;
    pageSize: number;
    current: number;
  };
}
class VTableWrapper extends React.Component<
  VTableWrapperProps,
  IVTableWrapperState
> {
  state: IVTableWrapperState = {
    dataSource: [],
    loading: false,
    pagination: {
      total: 0,
      pageSize: 10,
      current: 1,
    },
  };
  loadTableData = async () => {
    try {
      const { dataSource } = this.props;
      const { pagination } = this.state;
      this.setState({ loading: true });
      const res = await (dataSource as LoadTableFunc)({ pagination });
      this.setState({
        dataSource: res.list,
        pagination: {
          ...this.state.pagination,
          total: res.total,
        },
      });
    } catch (err) {
      message.error('加载表格数据失败');
    } finally {
      this.setState({ loading: false });
    }
  };
  setDataSource = () => {
    const { dataSource } = this.props;
    const { pagination } = this.state;
    if (Array.isArray(dataSource)) {
      this.setState({
        dataSource: dataSource,
        pagination: {
          ...pagination,
          total: dataSource.length,
        },
      });
    } else {
      this.loadTableData();
    }
  };
  componentDidMount() {
    this.setDataSource();
  }
  componentDidUpdate(prev: any) {
    if (this.props.reqParams !== prev?.reqParams) {
      this.setDataSource();
    }
    const newDataSourceConstr = this.props?.dataSource?.constructor;
    const oldDataSourceConstr = prev?.dataSource?.constructor;
    let newDataSourceStr = JSON.stringify(this.props?.dataSource);
    let oldDataSourceStr = JSON.stringify(prev?.dataSource);
    if (newDataSourceConstr instanceof Function) {
      newDataSourceStr = this.props?.dataSource?.toString();
    }
    if (oldDataSourceConstr instanceof Function) {
      oldDataSourceStr = prev?.dataSource?.toString();
    }
    if (newDataSourceStr !== oldDataSourceStr) {
      this.setDataSource();
    }
  }

  render() {
    const {
      title,
      rightBtn,
      columns,
      scrollX,
      scrollY,
      showPagination,
      showQuickJumper,
      pageSizeOptions,
      showTotal,
      extra,
    } = this.props;
    const { dataSource, loading, pagination } = this.state;
    const paginationConfig = {
      total: pagination.total,
      pageSize: pagination.pageSize,
      current: pagination.current,
      showTotal: showTotal ? (total: number) => `共 ${total} 条` : undefined,
      showSizeChanger: true,
      showQuickJumper: showQuickJumper,
      pageSizeOptions: pageSizeOptions ? ['10', '20', '50', '100'] : undefined,
    };
    return (
      <div className="v-table-wrapper">
        <div className="v-tabler-header">
          <h3>{title}</h3>
          <div className="v-header-right-slot">{rightBtn}</div>
        </div>
        <Table
          columns={columns as any}
          loading={loading}
          dataSource={dataSource}
          scroll={{ x: scrollX, y: scrollY }}
          {...extra}
          pagination={showPagination ? paginationConfig : false}
        ></Table>
      </div>
    );
  }
}

export default VTableWrapper;
